package com.xayq.orap.utils;

import org.apache.oltu.oauth2.common.OAuth;
import org.apache.oltu.oauth2.common.message.OAuthResponse;

import javax.servlet.http.HttpServletResponse;

import java.io.IOException;
import java.io.PrintWriter;
import java.math.BigInteger;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Map;


public class CommonUtils {


	public static String getMD5(String str) throws NoSuchAlgorithmException{

		// 生成一个MD5加密计算摘要
		MessageDigest md = MessageDigest.getInstance("MD5");
		// 计算md5函数
		md.update(str.getBytes());
		// digest()最后确定返回md5 hash值，返回值为8为字符串。因为md5 hash值是16位的hex值，实际上就是8位的字符
		// BigInteger函数则将8位的字符串转换成16位hex值，用字符串来表示；得到字符串形式的hash值
		return new BigInteger(1, md.digest()).toString(16);

	}


    public static void writeOAuthJsonResponse(HttpServletResponse response, OAuthResponse oAuthResponse) {

        int responseStatus = oAuthResponse.getResponseStatus();
        try {

            Map<String, String> headers = oAuthResponse.getHeaders();
            for (String key : headers.keySet()) {
                response.addHeader(key, headers.get(key));
            }
            // CORS setting
            response.setHeader("Access-Control-Allow-Origin", "*");
            response.setContentType(OAuth.ContentType.JSON);    //json
            response.setStatus(responseStatus);

            PrintWriter out = response.getWriter();
            out.print(oAuthResponse.getBody());
            out.flush();
        } catch (IOException e) {
            throw new IllegalStateException("Write OAuthResponse error", e);
        }
    }


    public static void writeOAuthQueryResponse(HttpServletResponse response, OAuthResponse oAuthResponse) {
        String locationUri = oAuthResponse.getLocationUri();
        try {

            Map<String, String> headers = oAuthResponse.getHeaders();
            for (String key : headers.keySet()) {
                response.addHeader(key, headers.get(key));
            }

            response.setStatus(oAuthResponse.getResponseStatus());
            response.sendRedirect(locationUri);

        } catch (IOException e) {
            throw new IllegalStateException("Write OAuthResponse error", e);
        }
    }



}